<script>
export default {
  name: 'FormCheckGroup',
  props: {
    label: {
      type: String,
      default: 'checkbox',
    },
    list: {
      type: Array,
      default: () => {
        return [{ text: '选项1', selected: true }, { text: '选项2', selected: false }]
      },
    },
    max: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      num: 0,
    }
  },
  mounted() {
    for (const item of this.list) {
      if (item.selected)
        this.num++
    }
  },
  methods: {
    select(item) {
      if (item) {
        if (item.selected && (this.max > 1 || this.list.length == 1)) {
          item.selected = false
          this.num--
          this.$emit('unselect', item)
        }
        else {
          if (this.max == 1) {
            for (const iit of this.list) {
              if (iit.selected && iit != item) {
                iit.selected = false
                this.num--
                this.$emit('unselect', iit)
              }
            }
            if (this.num == 0) {
              item.selected = true
              this.num++
              this.$emit('select', item)
            }
          }
          else if (this.num >= this.max) {
            // ElMessage.error('最多选择' + this.max + '个！');
          }
          else {
            item.selected = true
            this.num++
            this.$emit('select', item)
          }
        }
      }
    },
  },
}
</script>

<template>
  <view class="check-box">
    <view class="check-box-label">
      {{ label }}
    </view>
    <view class="form-check-group">
      <view v-for="(item, i) in list" :key="i" class="can-select" :class="{ selected: item.selected, noselected: item.selected }" @click="select(item)">
        <view>{{ item.text }}</view>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.check-box {
  display: flex;

  .check-box-label {
    width: 80px;
    padding: 5px 0;
    color: #726643;
    // font-weight: 700;
  }

  .form-check-group {
    color: #726643;
    display: flex;
    flex-wrap: wrap;
    margin: 5px 0 5px 10px;
    width: calc(100% - 90px);

    .can-select {
      cursor: pointer;
      position: relative;
      padding-left: 22px;
      margin-right: 10px;

      &::before {
        content: "";
        display: inline-block;
        position: absolute;
        left: 3px;
        top: 4px;
        width: 12px;
        height: 12px;
        background-image: url(https://www.tianyongxian.com:8018/dnfstatic/images/icons/base/checkbox_uncheck.png);
      }

      &.selected {
        color: #b59834;

        &::before {
          background-image: url(https://www.tianyongxian.com:8018/dnfstatic/images/icons/base/checkbox_checked.png);
        }
      }
    }
  }

}
</style>
